package aperturescience.resources;


//import org.restlet.data.Form;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Put;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

import aperturescience.types.ActionEngine;
import aperturescience.types.JSONMessageResponse;
import aperturescience.types.JSONPatient;
import aperturescience.wargames.WarGamesApplication;
import aperturescience.types.Action;

public class ActionEngineResource extends ServerResource {
/*
 * Input:	Patient (id number, we don't need whole patient)
 * 			Actions[] (list of actions to apply to the patient
 * 
 * Each action references a list of transitions: [(condition, transition), (condition, transition), ..., ]
 * 		Action:		Administer Tylenol
 * 		modifies:		[ (headache, minor_headache), (minor_headache, remove), (create, upset_stomach) ]
 * 			(create/remove are 'special' keywords within ActionEngineResource.)
 * 
 * The transition engine searches patient's State object for the conditions, and applies the transitions.
 * 
 * Post: modifies given Patient in the database, signals all views to update.
 * 
 * Output: nothing? or make a return to caller and let caller notify the clients
 */
		
	protected String patientId;
	protected String actionId;
	
	@Override
	protected void doInit() throws ResourceException
	{
		// Get the "patientId" attribute value taken from the URI template /patients/{patientId}.
		this.patientId = (String)getRequest().getAttributes().get("patientId");
		this.actionId = (String)getRequest().getAttributes().get("actionId");
	}
	
	/*@Post
	public JsonRepresentation postAE(Representation entity){
		Form form = new Form(entity);
		String actionId = form.getFirstValue("actionId");
		String patientId = form.getFirstValue("patientId");
		if (callEngine(actionId, patientId))
			return JSONMessageResponse.generateMessageRep("200", "Patient[" + patientId + "] updated");
		return JSONMessageResponse.generateMessageRep("501", "Error updating patient");
	}*/
	
	
	@Put
	public JsonRepresentation putAE(Representation entity){
		if (callEngine())
			return JSONMessageResponse.generateMessageRep("200", "Patient[" + patientId + "] updated");
		return JSONMessageResponse.generateMessageRep("501", "Error updating patient");
	}
	
	private boolean callEngine() {
		
		DatabaseResource db = new DatabaseResource(WarGamesApplication.couchdburl, WarGamesApplication.databasename);
		Action action = db.getAction(actionId);
		JSONPatient patient = db.getPatient(patientId);
		JSONPatient newPatient = ActionEngine.run(patient,action);
		if (newPatient==null)
			return false;
		db.updatePatient(newPatient,patientId);
		return true;
	}
	
}
